package com.we.flink.userlabelplatform.table;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;

public class TableUserAddress {
    public static final String KFKTABLE = "fdm.hhl01_user_address";
    public static final String QUERYSQL =
            "select uid, updated_at,"
                    + "education as audit_education "
                    + " from "
                    + KFKTABLE
                    + " where deleted_at is null "
                    + "and updated_at is not null "
                    + "and education is not null";

    public long uid;
    public int updated_at;
    public int audit_education;

    public TableUserAddress() {}

    public TableUserAddress(long uid, int updated_at, int audit_education) {
        this.uid = uid;
        this.updated_at = updated_at;
        this.audit_education = audit_education;
    }

    public static TableUserAddress init(long uid) {
        return new TableUserAddress(uid, Integer.MIN_VALUE, -1);
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableUserAddress.QUERYSQL);
        DataStream<Tuple2<Boolean, TableUserAddress>> inputStream =
                tableEnv.toRetractStream(tableRes, TableUserAddress.class);

        SingleOutputStreamOperator<String> out =
                inputStream
                        .filter(
                                new FilterFunction<Tuple2<Boolean, TableUserAddress>>() {
                                    @Override
                                    public boolean filter(Tuple2<Boolean, TableUserAddress> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .uid("TagUserAddress-filter")
                        .keyBy(
                                new KeySelector<Tuple2<Boolean, TableUserAddress>, Long>() {
                                    @Override
                                    public Long getKey(Tuple2<Boolean, TableUserAddress> value)
                                            throws Exception {
                                        return value.f1.getUid();
                                    }
                                })
                        .flatMap(
                                new RichFlatMapFunction<
                                        Tuple2<Boolean, TableUserAddress>, String>() {
                                    ValueState<TableUserAddress> tableUserAddressVSatate;

                                    @Override
                                    public void open(Configuration parameters) throws Exception {
                                        tableUserAddressVSatate =
                                                getRuntimeContext()
                                                        .getState(
                                                                new ValueStateDescriptor<
                                                                        TableUserAddress>(
                                                                        "TableUserAddressVSatate",
                                                                        TableUserAddress.class));
                                    }

                                    @Override
                                    public void flatMap(
                                            Tuple2<Boolean, TableUserAddress> value,
                                            Collector<String> out)
                                            throws Exception {
                                        long uid = value.f1.getUid();
                                        int updated_at = value.f1.getUpdated_at();
                                        int audit_education = value.f1.getAudit_education();

                                        TableUserAddress tmpState = tableUserAddressVSatate.value();
                                        TableUserAddress curSTate =
                                                tmpState == null
                                                        ? TableUserAddress.init(uid)
                                                        : tmpState;

                                        if (updated_at > curSTate.getUpdated_at()
                                                && audit_education != curSTate.audit_education) {
                                            JSONObject json = new JSONObject();
                                            json.put("uid", uid);
                                            json.put("audit_education", audit_education);

                                            out.collect(json.toString());

                                            curSTate.updated_at = updated_at;
                                            curSTate.audit_education = audit_education;
                                            tableUserAddressVSatate.update(curSTate);
                                        }
                                    }
                                });

        return out;
    }

    public long getUid() {
        return uid;
    }

    public int getUpdated_at() {
        return updated_at;
    }

    public int getAudit_education() {
        return audit_education;
    }
}
